
/*
 * Copyright (C) 2008-2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: TempdirSupport.java 137 2009-11-03 23:52:22Z archie.cobbs $
 */

package org.dellroad.sidekar;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

/**
 * Base class for unit tests that want to create a temporary directory
 * within which to work each time they run. The directory will be removed
 * upon shutdown.
 */
public abstract class TempdirSupport extends TestSupport {

    private static final FileFilter NORMAL_FILE_FILTER = new FileFilter() {
        public boolean accept(File subfile) {
            return !subfile.isDirectory();
        }
    };

    protected File tempdir;

    protected TempdirSupport() {
    }

    /**
     * This method creates the temporary directory within which {@link Test}-annotated
     * methods will operate.
     */
    @BeforeClass(dependsOnMethods = "setupLogging")
    public void setupTempdir() throws IOException {
        this.tempdir = File.createTempFile("sidekar.test.", "", null);
        log.debug("setting up temporary directory " + this.tempdir);
        this.tempdir.delete();
        if (!this.tempdir.mkdir())
            throw new IOException("can't create directory: " + this.tempdir);
    }

    /**
     * Clean-up method corresponding to {@link #setupTempdir}.
     */
    @AfterClass
    @Parameters({ "deleteTempDirs" })
    public void cleanupTempdir(boolean deleteTempDirs) {
        if (deleteTempDirs)
            removeAll(this.tempdir);
    }

    private void removeAll(File file) {

        // Delete files in directory
        if (file.isDirectory()) {
            for (File subfile : file.listFiles(NORMAL_FILE_FILTER))
                subfile.delete();
        }

        // Delete directory
        file.delete();
    }
}

